package uk.me.dewi.net.rest;

import java.net.URI;

import org.apache.http.client.methods.HttpRequestBase;

import uk.me.dewi.util.DataAccessException;

public class RestException extends DataAccessException {
    private static final long serialVersionUID = 1L;
    
    private String requestMethod;
    private URI uri;

    public RestException() {
        super();
    }

    public RestException(String detailMessage, Throwable throwable) {
        super(detailMessage, throwable);
    }

    public RestException(String detailMessage) {
        super(detailMessage);
    }

    public RestException(Throwable throwable) {
        super(throwable);
    }
    
    public RestException(HttpRequestBase request) {
        super();
        setRequest(request);
    }

    public RestException(String detailMessage, HttpRequestBase request, Throwable throwable) {
        super(detailMessage, throwable);
        setRequest(request);
    }

    public RestException(String detailMessage, HttpRequestBase request) {
        super(detailMessage);
        setRequest(request);
    }

    public RestException(HttpRequestBase request, Throwable throwable) {
        super(throwable);
        setRequest(request);
    }
    
    public RestException(HttpRequestBase request, String reasonPhrase) {
        super(reasonPhrase);
        setRequest(request);
    }

    private void setRequest(HttpRequestBase request){
        this.requestMethod = request.getMethod();
        this.uri = request.getURI();
    }
    
    /**
     * Return the detail message, including the message from the exception cause
     * if there is one.
     */
    @Override
    public String getMessage() {
        StringBuilder sb = new StringBuilder("RestException: ");
        if(super.getMessage() != null) sb.append(super.getMessage());
        if(requestMethod != null) sb.append(" in ").append(requestMethod)
                                     .append(" request for ").append(uri);
        if(this.getCause() != null){
            sb.append(" Caused By: ")
              .append(getCause().getMessage());
        }
        return sb.toString();
    }

}
